package com.xywy.me;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.xywy.R;
import com.xywy.common.BaseActivity;
import com.xywy.common.constants.ConstantValue;
import com.xywy.common.constants.ResultCode;
import com.xywy.common.net.AsyncHttpClient;
import com.xywy.common.net.OnResultListenerAdapter;
import com.xywy.common.net.Parser;
import com.xywy.common.util.FileUtil;
import com.xywy.common.util.MLog;
import com.xywy.common.widget.MyProgress;
import com.xywy.common.widget.TitleBar2;
import com.xywy.me.bean.Jtcy;
import com.xywy.me.bean.User;
import com.xywy.me.bean.UserKeeper;
import com.xywy.me.widget.ClipIconPopupWindow;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
 * 我 - 个人资料
 * 
 * @author xiaogd
 * 
 */
public class InforActivity extends BaseActivity {
	private static final String TAG = "InforActivity";

	private ImageView userIcon;
	private TextView tvAccount;
	private TextView tvSex;
	private TextView tvHeight;
	private TextView tvWeight;
	private TextView tvBirth;
	private Context mContext;
	private File iconFile;
	private User current_user;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 设置为全屏
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.me_infor);

		this.preInit();
		this.initView();
		this.loadData();
	}

//	private Jtcy jtcy;

//	private SharedPreferences sp;

//	private String userid;

	@Override
	public void preInit() {
		mContext = this.context;
//		Intent intent = this.getIntent();
//		jtcy = (Jtcy) intent.getSerializableExtra("jtcy");
//		jtcy = UserKeeper.getCurrentUser();
		myProgress = new MyProgress(this, 1);
//		sp = getSharedPreferences("config", Context.MODE_PRIVATE);
//        userid = sp.getString("userid", "");
		current_user = UserKeeper.getCurrentUser(this);
	}

	public void onClcikMeInfor(View view) {
		int item = 0;
		Intent intent = new Intent(InforActivity.this,
				InforUpdateActivity.class);
		switch (view.getId()) {
		case R.id.rl_me_infor_icon:
			// 当前页弹出选择icon popwindow,进行操作
			clipIcon();
			break;
		case R.id.rl_me_infor_name:
			item = ConstantValue.NAME;
			break;
		case R.id.rl_me_infor_sex:
			item = ConstantValue.SEX;
			break;
		case R.id.rl_me_infor_height:
			item = ConstantValue.HEIGHT;
			break;
		case R.id.rl_me_infor_weight:
			item = ConstantValue.WEIGHT;
			break;
		case R.id.rl_me_infor_brith:
			item = ConstantValue.BIRTH;
			break;
		}
		;
		if (item != 0) {
			MLog.i(TAG, "成员参数是=========：" + current_user.toString());
			intent.putExtra("item", item);
//			intent.putExtra("jtcy", jtcy);
			startActivity(intent);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		current_user = UserKeeper.getCurrentUser(this);
		System.out.println("1111111111111111   "+current_user.getSex());
//		jtcy = UserKeeper.getCurrentUser();
		if (current_user != null) {
			tvAccount.setText(current_user.getAccountstr());
			tvSex.setText(current_user.getSex());
			tvHeight.setText(current_user.getHeight());
//			tvWeight.setText(current_user.getWeight());
			tvBirth.setText(current_user.getBirthday());
			circleImageView(current_user.getAvatar(), userIcon);
			MLog.i(TAG, "主用户信息:====" + current_user.toString());
		}
	}

	@Override
	protected void onPause() {
		super.onPause();

	}

	@Override
	public void initView() {
		// title
		TitleBar2 titleBar = (TitleBar2) findViewById(R.id.me_infor_title_bar);
		titleBar.onClickBack(this);
		TextView tvTitle = titleBar.getTitle();
		TextView tvBack = titleBar.getTvBack();
		titleBar.getGo().setVisibility(View.INVISIBLE);
		tvTitle.setText(getString(R.string.me_infor_title));
		tvBack.setText(getString(R.string.me_infor_back));

		userIcon = (ImageView) findViewById(R.id.me_cover_userinfor_photo);

		tvAccount = (TextView) findViewById(R.id.tv_me_infor_accountstr);
		tvSex = (TextView) findViewById(R.id.tv_me_infor_sex);
		tvHeight = (TextView) findViewById(R.id.tv_me_infor_height);
		tvWeight = (TextView) findViewById(R.id.tv_me_infor_weight);
		tvBirth = (TextView) findViewById(R.id.tv_me_infor_birthday);
	}

	@Override
	public void loadData() {
	}

	// 圆形头像
	private void circleImageView(String url, ImageView imageView) {
		imageLoader.displayImage(url, imageView, options,
				new SimpleImageLoadingListener() {
					@Override
					public void onLoadingComplete(String imageUri, View view,
							Bitmap loadedImage) {
						if (loadedImage != null) {
							((ImageView) view)
									.setScaleType(ImageView.ScaleType.CENTER_CROP);
							boolean firstDisplay = !displayedImages
									.contains(imageUri);
							if (firstDisplay) {
								FadeInBitmapDisplayer.animate((ImageView) view,
										500);
								displayedImages.add(imageUri);
							}
						}
					}

					@Override
					public void onLoadingFailed(String imageUri, View view,
							FailReason failReason) {
						Throwable cause = failReason.getCause();
						MLog.e(TAG, cause.toString());
					}
				});
	}

	// ====ImageLoader start====
	public static final List<String> displayedImages = Collections
			.synchronizedList(new LinkedList<String>());
	// ImageLoaderOptions
	private DisplayImageOptions options;

	// ImageLoader
	protected ImageLoader imageLoader = ImageLoader.getInstance();

	private void initImageLoader() {
		options = new DisplayImageOptions.Builder()
				// .showImageForEmptyUri(R.drawable.ic_error) // resource or
				// drawable
				.showImageOnFail(R.drawable.imageloader_error)
				// resource or drawable
				.showStubImage(R.drawable.imageloader_default)
				.resetViewBeforeLoading(false)
				// default
				.cacheInMemory(true)
				.cacheOnDisc(true)
				// 精准
				.imageScaleType(ImageScaleType.EXACTLY)
				// ARGB_8888 每个像素要4字节~带透明度的颜色, 默认色样
				// RGB_565 每个像素要2字节~不带透明度的颜色
				.bitmapConfig(Bitmap.Config.RGB_565)
				.displayer(new RoundedBitmapDisplayer(10)).build();
	}

	// ====ImageLoader end====

	// 用来标识请求照相功能
	private String takePicturePath;// 调用相机拍摄照片的名字
	private String filePath;// 裁剪后图片的路径
	private String IMAGE_FILE_PATH = Environment.getExternalStorageDirectory()
			.getAbsolutePath() + "/head_pic";
	/**
	 * 点击头像 弹出popupWindow
	 */
	private ClipIconPopupWindow window;

	private void clipIcon() {
		// 实例化SelectPicPopupWindow
		window = new ClipIconPopupWindow(InforActivity.this, itemsOnClick);
		// 显示窗口
//		window.showAtLocation(findViewById(R.id.ll_me_infor), Gravity.CENTER
//				, 0, 0); // 设置layout在PopupWindow中显示的位置
		window.show();
	}

	// 为弹出窗口实现监听类
	private View.OnClickListener itemsOnClick = new View.OnClickListener() {
		public void onClick(View v) {
			window.dismiss();
			switch (v.getId()) {
			case R.id.btn_me_infor_clip_photo: // 拍照
				String sdStatus = Environment.getExternalStorageState();
				if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
					Toast.makeText(mContext, "未检测到内存卡", Toast.LENGTH_SHORT);
					return;
				}
				Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				// 下面这句指定调用相机拍照后的照片存储的路径
				takePicturePath = IMAGE_FILE_PATH + "/IMG"
						+ System.currentTimeMillis() + ".jpg";
				File image = new File(takePicturePath);
				intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(image));
				startActivityForResult(intent2, 2);
				if (window != null) {
					window.dismiss();
				}
				break;
			case R.id.btn_me_infor_clip_album: // 相册选择
				Intent intent = new Intent(Intent.ACTION_PICK, null);
				intent.setDataAndType(
						MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
				takePicturePath = getIntent().getStringExtra("data");
				startActivityForResult(intent, 1);
				if (window != null) {
					window.dismiss();
				}
				break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		MLog.i(TAG, "裁剪是否有返回 onActivityResult requestCode：" + requestCode);
		try {
			if (resultCode == RESULT_OK) {
				switch (requestCode) {
				// 如果是直接从相册获取
				case 1:
					startPhotoZoom(data.getData());
					break;
				// 如果是调用相机拍照时
				case 2:
					File temp = new File(takePicturePath);
					startPhotoZoom(Uri.fromFile(temp));
					break;
				// 取得裁剪后的图片
				case 3:
					if (data != null) {
						MLog.i(TAG, "裁剪是否有返回 onActivityResult data不为空");
						setPicToView(data);
					}
					break;
				default:
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 裁剪图片方法实现
	 * 
	 * @param uri
	 */
	public void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 150);
		intent.putExtra("outputY", 150);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, 3);
	}

	/**
	 * 保存裁剪之后的图片数据
	 * 
	 * @param picdata
	 */
	private void setPicToView(Intent picdata) {
		Bundle extras = picdata.getExtras();
		if (extras != null) {
			Bitmap bitmap = extras.getParcelable("data");
			FileOutputStream b = null;
			iconFile = new File(IMAGE_FILE_PATH);
			iconFile.mkdirs();
			filePath = IMAGE_FILE_PATH + "/" + System.currentTimeMillis()
					+ ".jpg";
			try {
				b = new FileOutputStream(filePath);
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
				// 上传到服务端
				this.sendMsg();

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					b.flush();
					b.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
				userIcon.setImageBitmap(bitmap);
			}
		}
	}

	MyProgress myProgress;
	JSONObject msgBack = null;
	int status = 0; // 上传后返回的状态 2：为成功
	String uploadUrl = ""; // 上传成功后的url
	int target = 1; // target:1：[上传头像] 2：[修改上传后的头像地址]
	/**
	 * 返回
	 */
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			MLog.i(TAG, "back:" + msg.obj + "resuletCode:" + msg.arg1);
			if (target == 2) {
				myProgress.stop();
			}
			if(msg.obj == null)
				return;
			try {
				msgBack = new JSONObject(msg.obj.toString());
			} catch (JSONException e) {
				e.printStackTrace();
			}
			if (target == 1) {
				status = msgBack.optInt("status");
				if (status == ResultCode.UPLOADICON) { // 上传成功后 再调用 修改头像的方法 [
														// status==2 等示成功]
					target = 2;
					uploadUrl = msgBack.optString("data");
					current_user.setAvatar(uploadUrl);
					UserKeeper.saveUser(current_user, InforActivity.this);
//					UserKeeper.setCurrentUser(jtcy);
//				    FileUtil.saveCurrentUser(userid + "mainaccount",
//	                		   jtcy);
//					sendMsg();
				} else {
					Toast.makeText(mContext,
							getString(R.string.me_upload_icon_fail),
							Toast.LENGTH_LONG).show();
				}
			} else if (target == 2) {
				status = msgBack.optInt("state");
				if (status != ResultCode.SUCCESS) { // 修改头像 失败
					Toast.makeText(mContext,
							getString(R.string.me_update_infor_fail),
							Toast.LENGTH_LONG).show();
				}
			}
		}
	};

	// 封装Parser参数
	private Parser paramsParser;
	// 封装httpclient参数
	private HashMap<String, Object> params;
	// 异步加载
	private AsyncHttpClient asyncHttpClient;

	// 处理网络请求
	public void sendMsg() {
		if (target == 1) {
			myProgress.start();
		}
		paramsParser = new Parser();
		// 封装参数
		params = new HashMap<String, Object>();

		// ================上传头像=============
		if (target == 1) {
			// 请求路径
			paramsParser.url = getString(R.string.me_infor_upload_icon);
			// 请求方式
			paramsParser.request = "upload";

			try {
				JSONObject object = new JSONObject();
				object.put("file", filePath);
				// 请求参数
				params.put("file", object);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		// ===============修改头像地址================
		if (target == 2) {
			// 请求路径
			paramsParser.action = getString(R.string.update_user_infor);
			// 请求方式
			paramsParser.request = "post";

			// 请求参数
			SharedPreferences sp = context.getSharedPreferences("config",
					Context.MODE_PRIVATE);
//			String userid = sp.getString("userid", "");
			params.put("userid", current_user.getUserid());
			params.put("keyword", "avatar");
			params.put("value", uploadUrl);
		}

		paramsParser.map = params;
		// 传递上下文
		paramsParser.context = this.context;

		asyncHttpClient = AsyncHttpClient.getInstance();
		asyncHttpClient.exeute(paramsParser, onResultListenerAdapter);
	}

	OnResultListenerAdapter onResultListenerAdapter = new OnResultListenerAdapter() {
		@Override
		public <T extends Parser> void onSuccess(T resultParser, int resultCode) {
			super.onSuccess(resultParser, resultCode);
			Message message = Message.obtain();
			message.arg1 = resultCode;
			message.obj = resultParser.back;
//			Log.e("messageavata", resultParser.back);
			handler.sendMessage(message);
		}
	};

}
